package com.zhoug.common.utils;

import android.annotation.SuppressLint;
import android.util.Log;

import com.zhoug.common.beans.ZDate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 描述：时间工具
 * zhougan
 * 2019/9/6
 **/
public class TimeUtils {
    private static final String TAG = "TimeUtils";
    public static final String PATTERN_DATE = "yyyy-MM-dd";
    public static final String PATTERN_TIME = "HH:mm";
    public static final String PATTERN_DATE_TIME = "yyyy-MM-dd HH:mm";
    public static final String PATTERN_HHMMSS = "HH:mm:ss";
    public static final String PATTERN = "yyyy-MM-dd HH:mm:ss";
    //2018-05-07T14:41:57.819+03:00
    public static final String yyyy_MM_dd_T_HH_mm_SSSZ = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";


    /**
     * 根据pattern获取SimpleDateFormat对象
     *
     * @param pattern 默认:yyyy-MM-dd HH:mm:ss
     * @return SimpleDateFormat
     */
    @SuppressLint("SimpleDateFormat")
    public static SimpleDateFormat getSimpleDateFormat(String pattern) {
        if (pattern == null) {
            pattern = PATTERN;
        }
        return new SimpleDateFormat(pattern);
    }

    /**
     * 获取当前时间
     *
     * @param pattern 默认 "yyyy-MM-dd HH:mm:ss"
     * @return
     */
    public static String getCurrentTime(String pattern) {
        return getSimpleDateFormat(pattern).format(new Date(System.currentTimeMillis()));
    }

    /**
     * 获取当前时间
     * 格式默认 "yyyy-MM-dd HH:mm:ss"
     *
     * @return
     */
    public static String getCurrentTime() {
        return getCurrentTime(PATTERN);
    }

    /**
     * Date to String
     *
     * @param date
     * @param pattern
     * @return
     */
    public static String format(Date date, String pattern) {
        return getSimpleDateFormat(pattern).format(date);
    }


    /**
     * long to String
     *
     * @param times
     * @param pattern
     * @return
     */
    public static String format(long times, String pattern) {
        return getSimpleDateFormat(pattern).format(times);
    }

    /**
     * String to date
     *
     * @param date
     * @param pattern
     * @return
     */
    public static Date parse(String date, String pattern) {
        try {
            return getSimpleDateFormat(pattern).parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 获取到从1900年到给定的年之间的年的集合
     *
     * @param endYear >1900
     * @return
     */
    public static ArrayList<String> getYearList(String endYear) {
        int endYearInt = Integer.parseInt(endYear);
        if (endYearInt <= 1900) {
            Log.e(TAG, "endYear must bigger 1900");
            return null;
        }

        ArrayList<String> years = new ArrayList<>();
        for (int i = 1900; i <= endYearInt; i++) {
            years.add(i + "");
        }
        return years;
    }

    /**
     * 获取12个月的集合{01，02....10,11,12}
     *
     * @return
     */
    public static ArrayList<String> getMonthList(String maxMonth) {
        if (StringUtils.isNullOrEmpty(maxMonth)) {
            maxMonth = "12";
        }
        int endMonth = 12;
        try {
            endMonth = Integer.parseInt(maxMonth);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        ArrayList<String> months = new ArrayList<>();
        for (int i = 1; i <= endMonth; i++) {
            if (i < 10) {
                months.add("0" + i);
            } else {
                months.add(i + "");
            }
        }
        return months;
    }

    /**
     * 获取24小时的集合{01，02....10,11,12}
     *
     * @return
     */
    public static ArrayList<String> getHourList() {
        ArrayList<String> months = new ArrayList<>();
        for (int i = 0; i <= 23; i++) {
            if (i < 10) {
                months.add("0" + i);
            } else {
                months.add(i + "");
            }
        }
        return months;
    }

    /**
     * 获取60分钟的集合{01，02....10,11,12}
     *
     * @return
     */
    public static ArrayList<String> getMinuteList() {
        ArrayList<String> months = new ArrayList<>();
        for (int i = 0; i <= 59; i++) {
            if (i < 10) {
                months.add("0" + i);
            } else {
                months.add(i + "");
            }
        }
        return months;
    }


    /**
     * 是否是闰年
     *
     * @param year
     * @return
     */
    public static boolean isLeapYear(String year) {
        return Integer.parseInt(year) % 4 == 0;
    }

    /**
     * 根据给定的年月获取当月的所有天的集合,数据传入第三个参数days中 ,如果days==null，则创建ArrayList
     *
     * @param year  年
     * @param month 月
     * @param days  数据传入ArrayList
     * @return days
     */
    public static ArrayList<String> getDays(String year, String month, ArrayList<String> days) {
        if (days == null) {
            days = new ArrayList<>();
        } else {
            days.clear();
        }
        int yearInt = Integer.parseInt(year);
        int monthInt = Integer.parseInt(month);
        int maxDay = 0;//最大天数
        if (monthInt == 1 || monthInt == 3 || monthInt == 5 || monthInt == 7 || monthInt == 8 || monthInt == 10 || monthInt == 12) {
            maxDay = 31;
        } else if (monthInt == 2) {
            maxDay = yearInt % 4 == 0 ? 29 : 28;
        } else {
            maxDay = 30;
        }

        for (int i = 1; i <= maxDay; i++) {
            if (i < 10) {
                days.add("0" + i);
            } else {
                days.add(i + "");
            }
        }
        return days;
    }

    /**
     * 根据给定的年月获取当月的所有天的集合
     *
     * @param year
     * @param month
     * @return
     */
    public static ArrayList<String> getDays(String year, String month) {
        return getDays(year, month, null);
    }


    /**
     * 获取当月的最后一天是几号
     *
     * @param year
     * @param month
     * @return
     */
    public static int getLastDay(int year, int month) {
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
            return 31;
        } else if (month == 2) {
            return year % 4 == 0 ? 29 : 28;
        } else {
            return 30;
        }
    }

    /**
     * 把日期中的separator换成" ",并且最多保留到秒
     *
     * @param date      eg:2019-08-25T12:36:55
     * @param separator 年月日和时间之间的分隔符 默认"T"
     * @return dateString
     */
    public static String formatDateT(String date, String separator) {
        if (date == null) {
            return null;
        }
        if (separator == null) {
            separator = "T";
        }

        if (date.contains(separator)) {
            date = date.replace(separator, " ");
        }
        if (date.length() > 19) {
            date = date.substring(0, 19);
        }

        return date;
    }

    /**
     * 把日期中的T换成" ",并且最多保留到秒
     *
     * @param date eg:2019-08-25T12:36:55
     * @return dateString
     */
    public static String formatDateT(String date) {
        return formatDateT(date, "T");
    }

    /**
     * 获取日期中的年月日
     *
     * @param date eg:2019-08-25T12:36:55
     * @return
     */
    public static String formatDateYMD(String date) {
        if (date == null) {
            return null;
        }
        if (date.length() >= 10) {
            return date.substring(0, 10);
        } else {
            return date;
        }
    }

    /**
     * 获取日期中的时分秒
     *
     * @param date eg:2019-08-25T12:36:55
     * @return
     */
    public static String formatDateHMS(String date) {
        if (date == null) {
            return null;
        }
        if (date.length() > 10) {
            //T12:36:55
            String time = date.substring(10);
            //T
            String first = time.substring(0, 1);
            try {
                //判断是否是数字
                int i = Integer.parseInt(first);
            } catch (NumberFormatException e) {
//                e.printStackTrace();
                //第一个不是数字
                time = time.replace(first, "").trim();
            }
            //12:36:55
            if (time.length() > 8) {
                return time.substring(0, 8);
            } else {
                return time;
            }
        }
        return null;
    }


    /**
     * 将Calendar格式化为"2018-05-07T14:41:57.819+03:00",转换为手机设备所在时区
     *
     * @param calender calenderTime
     * @return 格式化时间字符串
     */
    public static String calenderToyyyy_MM_dd_T_HH_mm_SSSZ(Calendar calender) {
        if (null == calender) {
            Log.e(TAG, "convertToString : The calender time is null");
            return "";
        }
        return formatToyyyy_MM_dd_T_HH_mm_SSSZ(calender.getTime());
    }

    /**
     * @param formatTime "2018-05-07T14:41:57.819+03:00",转换为手机设备所在时区
     * @return
     */
    public static Date parseyyyy_MM_dd_T_HH_mm_SSSZ(String formatTime) {
        StringBuilder builder = new StringBuilder(formatTime);
        if (formatTime.length() > 26) {
            builder.deleteCharAt(26);
        } else {
            LogUtils.e(TAG, "yyyy_MM_dd_T_HH_mm_SSSZToCalendar:formatTime=" + formatTime);
        }
        SimpleDateFormat sdf = new SimpleDateFormat(yyyy_MM_dd_T_HH_mm_SSSZ, Locale.getDefault());
        try {
            return sdf.parse(formatTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 将时间格式化为"2018-05-07T14:41:57.819+03:00",转换为手机设备所在时区
     *
     * @param date calenderTime
     * @return 格式化时间字符串
     */
    public static String formatToyyyy_MM_dd_T_HH_mm_SSSZ(Date date) {
        if (null == date) {
            Log.e(TAG, "convertToString : date is null");
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(yyyy_MM_dd_T_HH_mm_SSSZ, Locale.getDefault());
        StringBuilder builder = new StringBuilder(sdf.format(date));
        builder.insert(26, ":");
        return builder.toString();
    }

    /**
     * 将时间格式化为"2018-05-07T14:41:57.819+03:00",转换为手机设备所在时区
     *
     * @param time calenderTime
     * @return 格式化时间字符串
     */
    public static String formatToyyyy_MM_dd_T_HH_mm_SSSZ(long time) {
        if (0 >= time) {
            Log.e(TAG, "convertToString : time 必须大于0");
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(yyyy_MM_dd_T_HH_mm_SSSZ, Locale.getDefault());
        StringBuilder builder = new StringBuilder(sdf.format(new Date(time)));
        builder.insert(26, ":");
        return formatToyyyy_MM_dd_T_HH_mm_SSSZ(new Date(time));
    }


    /**
     * 比较2个时间的大小
     *
     * @param startTime
     * @param endTime
     * @param format    yyyy-MM-dd HH:mm:ss 2个时间格式需要满足
     * @return 0:相等; 1:startTime>endTime;-1:startTime<endTime
     */
    public static int compareTime(String startTime, String endTime, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.getDefault());
        LogUtils.d(TAG, "compareTime:startTime=" + startTime);
        LogUtils.d(TAG, "compareTime:endTime=" + endTime);
        try {
            Date date1 = simpleDateFormat.parse(startTime);
            Date date2 = simpleDateFormat.parse(endTime);
            LogUtils.d(TAG, "compareTime:date1=" + date1.getTime());
            LogUtils.d(TAG, "compareTime:date2=" + date2.getTime());
            long result = date1.getTime() - date2.getTime();
            if (result > 0) {
                return 1;
            } else if (result < 0) {
                return -1;
            } else {
                return 0;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            LogUtils.e(TAG, "compareTime:" + e.getMessage());
        }
        return 0;
    }

    /**
     * 获取星期几
     *
     * @param date
     * @return
     */
    public static String getWeek(Date date) {
        if (date == null) {
            return null;
        }

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int wek = c.get(Calendar.DAY_OF_WEEK);
        String week = null;
        if (wek == 1) {
            week = "星期日";
        }
        if (wek == 2) {
            week = "星期一";
        }
        if (wek == 3) {
            week = "星期二";
        }
        if (wek == 4) {
            week = "星期三";
        }
        if (wek == 5) {
            week = "星期四";
        }
        if (wek == 6) {
            week = "星期五";
        }
        if (wek == 7) {
            week = "星期六";
        }
        LogUtils.d(TAG, "getWeek:week=" + week);
        return week;

    }

    public static int getWeek1(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int i = c.get(Calendar.DAY_OF_WEEK);
        if (i == 1) {
            return 7;
        } else {
            return i - 1;
        }

    }

    /**
     * 年
     *
     * @param date
     * @return
     */
    public static int getYear(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.YEAR);
    }

    /**
     * 月
     *
     * @param date
     * @return
     */
    public static int getMonth(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.MONTH) + 1;
    }

    /**
     * 日
     *
     * @param date
     * @return
     */
    public static int getDay(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 时
     *
     * @param date
     * @return
     */
    public static int getHour(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.HOUR);
    }

    /**
     * 分
     *
     * @param date
     * @return
     */
    public static int getMinute(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.MINUTE);
    }


    /**
     * 比较2个数字字符串的大小
     *
     * @param s1
     * @param s2
     * @return
     */
    public static int compareInt(String s1, String s2) {
        try {
            int i = Integer.parseInt(s1);
            int i1 = Integer.parseInt(s2);
            return i - i1;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        return 0;
    }

    /**
     * 各位数添加0
     *
     * @param num 2
     * @return 02
     */
    public static String addZero(String num) {
        if (num != null && num.length() == 1) {
            return "0" + num;
        }
        return num;
    }

    /**
     * 各位数添加0
     *
     * @param num 2
     * @return 02
     */
    public static String addZero(int num) {
        return addZero(String.valueOf(num));
    }


    /**
     * 在给定的时间上加上指定的天数
     *
     * @param date
     * @param year
     * @param format
     * @return
     */
    public static String addYear(@NonNull String date, int year, @NonNull String format) {
        Date parse = parse(date, format);
        if (parse != null) {
            Date date1 = addYear(parse, year);
            if (date1 != null) {
                return format(date1, format);
            }
        }
        return null;
    }

    /**
     * 获取本月
     *
     * @return
     */
    public static int getCurrentMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(System.currentTimeMillis()));
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     * 获取当年
     *
     * @return
     */
    public static int getCurrentYear() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(System.currentTimeMillis()));
        return calendar.get(Calendar.YEAR);
    }

    /**
     * @param second
     * @return HH:mm:ss
     */
    public static String formatSecond(int second) {
        if (second <= 0) {
            return "00:00";
        } else if (second < 60) {
            //1分钟以内
            if (second < 10) {
                return "00:0" + second;
            } else {
                return "00:" + second;
            }
        } else if (second < 3600) {
            //一小时内
            int m = second / 60;
            int s = second % 60;
            String strm = "" + m;
            String strs = "" + s;
            if (m < 10) {
                strm = "0" + m;
            }
            if (s < 10) {
                strs = "0" + s;
            }
            return strm + ":" + strs;
        } else {
            //一小时以上
            int h = second / 3600;
            second = second % 3600;//剩余的秒数
            int m = second / 60;
            int s = second % 60;
            String strh = "" + h;
            String strm = "" + m;
            String strs = "" + s;
            if (h < 10) {
                strh = "0" + h;
            }
            if (m < 10) {
                strm = "0" + m;
            }
            if (s < 10) {
                strs = "0" + s;
            }
            return strh + ":" + strm + ":" + strs;
        }
    }

    /**
     * 给定的时间加上天数
     *
     * @param day
     * @return
     */
    public static Date addDay(Date date, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_YEAR, day);
        return calendar.getTime();
    }

    /**
     * 在给定的时间上加上指定的年
     *
     * @param date 给定的时间
     * @param year 正数加,负数减
     * @return
     */
    public static Date addYear(@NonNull Date date, int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, year);
        return calendar.getTime();
    }

    /**
     * 在给定的时间上加上指定的月
     *
     * @param date  给定的时间
     * @param month 正数加,负数减
     * @return
     */
    public static Date addMonth(@NonNull Date date, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, month);
        return calendar.getTime();
    }

    public static @Nullable
    ZDate findYMD(String time) {
        if (StringUtils.isNullOrEmpty(time)) return null;
        try {
            Pattern pattern = Pattern.compile("(\\d{4})[-\\.\\/年]?(\\d{2})[-\\.\\/月]?(\\d{2})[-\\.\\/日号]?");
            Matcher matcher = pattern.matcher(time);
            if (matcher.find()) {
                ZDate zDate = new ZDate();
                zDate.setYear(matcher.group(1));
                zDate.setMonth(matcher.group(2));
                zDate.setDay(matcher.group(3));
                return zDate;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取开始日期到结束日期之间的全部日期
     *
     * @param startTime 开启日期
     * @param endTime   结束日期
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static List<String> getMiddleTimes(String startTime, String endTime) {
        List<String> result = new ArrayList<>();
        if (!StringUtils.isNullOrEmpty(startTime) && !StringUtils.isNullOrEmpty(endTime)) {
            try {
                final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date tempDate = new Date();
                //找到年月日
                ZDate times1 = findYMD(startTime);
                ZDate times2 = findYMD(endTime);
                if (times1 != null && times2 != null) {
                    Calendar calendar = Calendar.getInstance(Locale.CHINA);
                    calendar.set(Integer.parseInt(times2.getYear()), Integer.parseInt(times2.getMonth()) - 1, Integer.parseInt(times2.getDay()));
                    //结束日期
                    final long endTimeInMillis = calendar.getTimeInMillis();
                    calendar.set(Integer.parseInt(times1.getYear()), Integer.parseInt(times1.getMonth()) - 1, Integer.parseInt(times1.getDay()));
                    //开始日期
                    long startTimeInMillis = calendar.getTimeInMillis();
                    if (startTimeInMillis == endTimeInMillis) {
                        tempDate.setTime(startTimeInMillis);
                        result.add(simpleDateFormat.format(tempDate));
                    } else if (startTimeInMillis < endTimeInMillis) {
                        while (startTimeInMillis < endTimeInMillis) {
                            tempDate.setTime(startTimeInMillis);
                            result.add(simpleDateFormat.format(tempDate));
                            calendar.add(Calendar.DAY_OF_YEAR, 1);
                            startTimeInMillis = calendar.getTimeInMillis();
                        }
                        tempDate.setTime(endTimeInMillis);
                        result.add(simpleDateFormat.format(tempDate));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

}
